package com.example.financeapi.job;

import com.alibaba.fastjson.JSONObject;
import com.example.financeapi.config.annotation.SystemJobLog;
import com.example.financeapi.config.constant.APIConstant;
import com.example.financeapi.entity.FNewdebt;
import com.example.financeapi.entity.FTaskErrorLog;
import com.example.financeapi.mapper.FTaskErrorLogMapper;
import com.example.financeapi.service.FNewdebtService;
import com.example.financeapi.utils.HttpUtil;
import com.example.financeapi.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   //2.开启定时任务
public class PurchaseTask {

    @Autowired
    private FTaskErrorLogMapper fTaskErrorLogMapper;

    @Autowired
    private FNewdebtService fNewdebtService;

    @Async
    @SystemJobLog(description = "每天1小时10分获取一下新债信息")
    @Scheduled(cron = "0 10 0/1 * * ?")
    //@Scheduled(cron = "0 0/2 * * * ?")
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
    public void getNewDebtInfo() {
        List<FNewdebt> todayList;
        List<FNewdebt> futureList;
        List<FNewdebt> listedList;
        String getNewDebtApi = APIConstant.GET_NEWDEBT_URL;
        String getDate =LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        try {
            String JsonStr = HttpUtil.httpGet(getNewDebtApi);
            JSONObject jsonObj = JSONObject.parseObject(JsonStr);
            int code = Integer.parseInt(jsonObj.get("code")+"");
            if(code == 0){
                JSONObject dataObj = (JSONObject) jsonObj.get("result");
                String todayStr = dataObj.get("today").toString();
                String futureStr = dataObj.get("future").toString();
                String listedStr = dataObj.get("listed").toString();
                /**今日发行*/
                todayList = JsonUtils.jsonToList(todayStr, FNewdebt.class);
                if(todayList ==null){
                    todayList = JsonUtils.jsonToListTwo(todayStr, FNewdebt.class);
                }
                if(!CollectionUtils.isEmpty(todayList)){
                    todayList.forEach(fNewdebt -> {
                        FNewdebt newdebt =fNewdebtService.queryById(fNewdebt.getId());
                        if(newdebt==null){
                            fNewdebt.setIssuingState(1);
                            fNewdebtService.insert(fNewdebt);
                        }else{
                            //更新状态
                            String psnSubDtOn =newdebt.getPsnSubDtOn()+"";
                            if(psnSubDtOn.equals(getDate)){
                                newdebt.setIssuingState(1);
                                fNewdebtService.update(newdebt);
                            }
                        }
                    });
                }

                 /**即将发行*/
                futureList = JsonUtils.jsonToList(futureStr, FNewdebt.class);
                if(futureList ==null){
                    futureList = JsonUtils.jsonToListTwo(futureStr, FNewdebt.class);
                }
                if(!CollectionUtils.isEmpty(futureList)){
                    futureList.forEach(fNewdebt -> {
                        FNewdebt futureNewdebt =fNewdebtService.queryById(fNewdebt.getId());
                        if(futureNewdebt==null){
                            fNewdebt.setIssuingState(0);
                            fNewdebtService.insert(fNewdebt);
                        }else{
                            //更新状态
                            String psnSubDtOn =futureNewdebt.getPsnSubDtOn()+"";
                            if(psnSubDtOn.equals(getDate)){
                                futureNewdebt.setIssuingState(0);
                                fNewdebtService.update(futureNewdebt);
                            }
                        }
                    });
                }

                 /**已发行*/
                listedList = JsonUtils.jsonToList(listedStr, FNewdebt.class);
                if(listedList ==null){
                    listedList = JsonUtils.jsonToListTwo(listedStr, FNewdebt.class);
                }
                if(!CollectionUtils.isEmpty(listedList)){
                    listedList.forEach(fNewdebt -> {
                        FNewdebt listedNewdebt =fNewdebtService.queryById(fNewdebt.getId());
                        if(listedNewdebt==null){
                            fNewdebt.setIssuingState(2);
                            fNewdebtService.insert(fNewdebt);
                        }else{
                            //更新状态
                            String psnSubDtOn =listedNewdebt.getPsnSubDtOn()+"";
                            if(psnSubDtOn.equals(getDate)){
                                listedNewdebt.setIssuingState(2);
                                fNewdebtService.update(listedNewdebt);
                            }
                        }
                    });
                }
            }
        } catch (Exception ex) {
            FTaskErrorLog fTaskErrorLog =new FTaskErrorLog();
            fTaskErrorLog.setTaskName(this.getClass().getName());
            fTaskErrorLog.setMessage(ex.getMessage());
            fTaskErrorLog.setCause(ex.getCause()+"");
            fTaskErrorLogMapper.insert(fTaskErrorLog);
            log.error("【定时任务 getNewDebtInfo】定时刷新出现异常：{}，原因：{} ,msg={}", ex.getMessage(), ex.getCause(),ex);
        }
    }
}
